package service

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"time"
	"video_src/basic/appConfig"
	__ "video_src/basic/proto"
	"video_src/handler/models"
)

// server is used to implement helloworld.GreeterServer.
type Server struct {
	__.UnimplementedVideoServer
}

func (s *Server) AddVideo(_ context.Context, in *__.AddVideoReq) (*__.AddVideoResp, error) {
	var err error
	var v models.Video

	v.Title = in.Title
	v.Briefly = in.Desc
	v.TypesId = in.TypesId
	v.Ads = in.Ads
	v.Channel = in.Channel
	v.CoverUrl = in.CoverUrl
	v.PlayUrl = in.PlayUrl
	if err = v.CreateVideo(appConfig.DB); err != nil {
		return nil, errors.New("视频信息录入失败")
	}

	return &__.AddVideoResp{
		Id: int64(v.ID),
	}, nil
}

func (s *Server) CheckVideo(_ context.Context, in *__.CheckVideoReq) (*__.CheckVideoResp, error) {
	var err error
	var v models.Video
	var msg string

	v.CheckStatus = in.Status
	v.CheckReason = in.CheckReason

	if err = v.UpdateCheckStatus(appConfig.DB, in.VideoId, in.Status); err != nil {
		return nil, errors.New("视频审核状态异常")
	}
	if err = v.UpdateCheckReason(appConfig.DB, in.VideoId, in.CheckReason); err != nil {
		return nil, errors.New("审核备注添加失败")
	}
	if v.CheckStatus == 1 {
		msg = "视频通过审核"
	} else if v.CheckStatus == 2 {
		msg = "驳回申请"
	}

	return &__.CheckVideoResp{
		VideoId: in.VideoId,
		Msg:     msg,
	}, nil
}

func (s *Server) VideoList(_ context.Context, in *__.VideoListReq) (*__.VideoListResp, error) {
	var err error
	var vs models.Video
	var vsl []models.Video
	var vsList []*__.ListVideo

	key := fmt.Sprintf("video:channel:%d", in.Channel)

	cacheData, _ := appConfig.Rdb.Get(appConfig.Ctx, key).Result()
	if cacheData == "" {
		vsl, err = vs.VideoList(appConfig.DB)
		if err != nil {
			return nil, errors.New("列表获取失败")
		}
		jsonData, _ := json.Marshal(vsl)
		appConfig.Rdb.Set(appConfig.Ctx, key, jsonData, time.Hour)
	} else {
		err := json.Unmarshal([]byte(cacheData), &vsl)
		if err != nil {
			return nil, err
		}
	}

	for _, v := range vsl {
		list := __.ListVideo{
			Id:        int64(v.ID),
			Title:     v.Title,
			Score:     float32(v.Score),
			PlayCount: v.PlayCount,
			CoverUrl:  v.CoverUrl,
		}
		vsList = append(vsList, &list)
	}
	return &__.VideoListResp{
		List: vsList,
	}, nil
}

func (s *Server) VideoInfo(_ context.Context, in *__.VideoInfoReq) (*__.VideoInfoResp, error) {
	var v models.Video
	var err error

	if err = v.GetVideoById(appConfig.DB, in.VideoId); err != nil {
		return nil, errors.New("视频信息获取失败")
	}

	return &__.VideoInfoResp{
		VideoId:   int64(v.ID),
		Title:     v.Title,
		Desc:      v.Briefly,
		LeadActor: v.LeadActor,
		Director:  v.Director,
		PlayCount: v.PlayCount,
	}, nil
}
